<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区 -->
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <!-- 搜索与添加区域 -->
        <el-row :gutter="20">
          <el-col :span="2">
            <el-button type="primary" @click="dialogVisibleAddShow">添加</el-button>
          </el-col>
          <el-col :span="8"></el-col>
        </el-row>
      </div>

      <zk-table
        :data="productsTypeList"
        :columns="columns"
        :selection-type="false"
        :expand-type="false"
        :show-index="true"
        index-text="#"
        :border="true"
        :show-row-hover="true"
      >
        <!-- 是否启用 -->
        <template slot="istrue" slot-scope="{row}">
          <i class="el-icon-success Success" v-if="row.deleted === false" style="color:#1989fa"></i>
          <i class="el-icon-error danger" v-if="row.deleted === true" style="color:#ff0000"></i>
        </template>
        <!-- 排序 -->
        <template slot="sort" slot-scope="{row}">
          <el-tag effect="dark" size="mini" v-if="row.level === 0" type>一级</el-tag>
          <el-tag effect="dark" size="mini" v-if="row.level === 1" type="success">二级</el-tag>
          <el-tag effect="dark" size="mini" v-if="row.level === 2" type="warning">三级</el-tag>
        </template>
        <!-- 操作 -->
        <template slot="op" slot-scope="{row}">
          <!-- 修改 -->
          <el-button
            type="primary"
            icon="el-icon-edit"
            circle
            size="mini"
            @click="dialogVisibleEditShow(row.id)"
          ></el-button>

          <!-- 删除 -->
          <el-button
            type="danger"
            icon="el-icon-delete"
            circle
            size="mini"
            @click="deleteById(row.id)"
          ></el-button>
        </template>
      </zk-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pageNum"
        :page-sizes="pageSizes"
        :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>

    <!-- 添加分类对话框 -->
    <el-dialog title="添加" :visible.sync="dialogVisibleAdd" width="30%" @close="addFormClear">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
        <!-- 提示信息 -->
        <el-alert
          style="margin-bottom:15px"
          title="提示：父级分类最多选到 二 级"
          type="warning"
          :show-icon="true"
        ></el-alert>
        <el-form-item label="活动名称" prop="name">
          <el-input v-model="addForm.name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
          <!-- options 绑定数据源 -->
          <!-- props 绑定配置对象 -->
          <el-cascader
            style="width:100%"
            placeholder="试试搜索"
            expand-trigger="hover"
            :options="parentProductsType"
            :props="cascaderProps"
            v-model="selectedIds"
            :filterable="true"
            :clearable="true"
            :change-on-select="true"
            @change="cascaderChanged"
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addFormOp">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改对话框 -->
    <el-dialog title="修改" :visible.sync="dialogVisibleEdit" width="50%">
      修改的form
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleEdit = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisibleEdit=false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>


<script>
export default {
  data() {
    return {
      // 获取商品分类列表的参数
      queryInfo: {
        type: 1,
        pageNum: 1,
        pageSize: 10,
      },
      // 分頁組件
      pageSizes: [10, 15, 20],
      // 记录总条数
      total: 0,
      // 默认商品分类数据为空
      productsTypeList: [],
      // 为table指定列
      columns: [
        {
          label: '名称',
          prop: 'name',
        },
        {
          label: '启用状态',
          // 表示当前列定义为模板列
          type: 'template',
          // 表示当前列使用的模板名称
          template: 'istrue',
        },
        {
          label: '分级',
          type: 'template',
          template: 'sort',
        },
        {
          label: '操作',
          type: 'template',
          template: 'op',
        },
      ],
      // 添加对话框
      dialogVisibleAdd: false,
      // 添加数据
      addForm: {
        name: '',
        pid: 0,
        level: 0,
      },
      // 添加表单规则
      addFormRules: {
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        pid: [],
        level: [],
      },
      // 父级分类的数据
      parentProductsType: [],
      // 级联选择器的绑定配置对象
      cascaderProps: {
        value: 'id',
        label: 'name',
        children: 'children',
        // checkStrictly: true
      },
      // 选中的父级分类的id数组
      selectedIds: [],
      dialogVisibleEdit: false,
    }
  },
  created() {
    this.getProductsTypeList()
  },
  methods: {
    // 获取商品分页
    async getProductsTypeList() {
      await this.$http
        .get('/productsType', { params: this.queryInfo })
        .then((res) => {
          res = res.data
          // console.log(res)
          if (!res.code || res.code == 0)
            return this.$message.error(res.msg || '获取数据失败')

          this.productsTypeList = res.data.list
          this.total = res.data.total
        })
        .catch((err) => {
          return this.$message.error(err.message || '获取失败')
        })
    },
    // 监听 pagesize 改变的事件
    handleSizeChange(val) {
      this.queryInfo.pageSize = val
      this.getProductsTypeList()
    },
    // 监听页码值改变的事件
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`)
      this.queryInfo.pageNum = val
      this.getProductsTypeList()
    },
    // 删除为空的子节点
    deleteEmptyChildren(obj) {
      // console.log(obj)
      function traversal(data) {
        for (var item of data) {
          if (item.children) {
            if (item.children.length > 0) {
              traversal(item.children)
            }
            if (item.children.length === 0) {
              delete item.children
            }
          }
        }
      }

      traversal(obj)
    },
    // 添加对话框显示
    async dialogVisibleAddShow() {
      // 获取父级分类数据
      await this.$http
        .get('/productsType', { params: { type: 2 }})
        .then((res) => {
          res = res.data
          // console.log(res)
          if (!res.code || res.code == 0)
            return this.$message.error(res.msg || '获取数据失败')

          this.parentProductsType = res.data.list

          this.deleteEmptyChildren(this.parentProductsType)

          this.dialogVisibleAdd = true
        })
        .catch((err) => {
          return this.$message.error(err.message || '获取失败')
        })
    },
    cascaderChanged() {
      // console.log(this.selectedIds)
      if (this.selectedIds.length > 2) {
        this.selectedIds = []
        return
      }

      if (this.selectedIds.length > 0) {
        this.addForm.pid = this.selectedIds[this.selectedIds.length - 1]
        this.addForm.level = this.selectedIds.length
      } else {
        this.addForm.pid = 0
        this.addForm.level = 0
      }
    },
    addFormClear() {
      this.$refs.addFormRef.resetFields()
      this.selectedIds = []
      this.addForm.name = ''
      this.addForm.pid = 0
      this.addForm.level = 0
    },
    addFormOp() {
      this.$refs.addFormRef.validate(async (validate) => {
        if (!validate) return

        await this.$http
          .post('productsType', this.addForm)
          .then((res) => {
            res = res.data
            // console.log(res)

            if (!res.code || res.code == 0)
              return this.$message.error(res.msg || '获取数据失败')

            this.dialogVisibleAdd = false
            this.getProductsTypeList()
            return this.$message.success(res.msg || '操作成功')
          })
          .catch((err) => {
            return this.$message.error(err.message || '操作失败')
          })
      })
    },
    dialogVisibleEditShow(id) {
      console.log(id)
      this.dialogVisibleEdit = true
    },
    async deleteById(id) {
      await this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          console.log(id)
        })
        .catch(() => {
          this.$message.info('已取消删除')
        })
    },
    // 获取父级分类列表数据
    // getParentTypeList() {}
  },
}
</script>

<style lang="scss" scoped>
</style>